package com.itheima.dubbo.api.mongo.Impl;

import com.itheima.dubbo.api.mongo.VideoApi;
import com.itheima.dubbo.utils.IdWorker;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    /**
     * 保存小视频
     * @param video
     */
    @Override
    public void save(Video video) {
        video.setVid(idWorker.getNextId("video"));
        mongoTemplate.save(video);
    }


    /**
     * 视频列表
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public PageResult findAll(Integer page, Integer pagesize) {
        Query query = new Query();
        Long count = mongoTemplate.count(query,Video.class);
        query.skip((page-1)*pagesize).limit(pagesize);
        List<Video> videoList = mongoTemplate.find(query,Video.class);
        return new PageResult(page.longValue(),pagesize.longValue(),count,videoList);
    }

    @Override
    public PageResult findByUid(Long uid, Integer page, Integer pagesize) {
        Query query = new Query(Criteria.where("userId").is(uid));
        long count = mongoTemplate.count(query, Video.class);
        query.skip((page-1)*pagesize).limit(pagesize).with(Sort.by(Sort.Order.desc("created")));
        List<Video> videoList = mongoTemplate.find(query, Video.class);

        return new PageResult(page.longValue(),pagesize.longValue(),count,videoList);
    }
}